﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using SignalR.Web.LogHelper;
using SignalR.Web.Models;
using System.Security.Claims;

namespace SignalR.Web.Hubs
{
	public class ChatHub : Hub
	{
		private readonly ILogger<ChatHub> _logger;
		private IMemoryCache _cache;

		public ChatHub(ILogger<ChatHub> logger, IMemoryCache cache)
		{
			_logger = logger;
			_cache = cache;
		}

		/// <summary>
		/// 给所有客户端发送消息
		/// </summary>
		/// <param name="user">用户</param>
		/// <param name="message">消息</param>
		/// <returns></returns>
		public async Task SendMessage(string user, string message)
		{
			_logger.LogInformation($"SendMessage===== {user} {message}");

			var userinfo = WebConst.GetOnlineUser(user);
			ResultModel result = new ResultModel()
			{
				Code = 0,
				Msg = user + "====说====" + message,
				OnlineUser = WebConst.OnlineUserList.FindAll(u => u.GroupName == userinfo?.GroupName)
			};

			await Clients.Group(userinfo?.GroupName ?? "Group2").SendAsync("GetUsersResponse", result);

			if (userinfo == null)
			{
				await Clients.All.SendAsync("ReceiveMessage", result);
			}
			else
			{
				await Clients.Client(userinfo.ConnectionId).SendAsync("ReceiveMessage", result);
			}
		}

		/// <summary>
		/// 向调用客户端发送消息
		/// </summary>
		/// <param name="message"></param>
		/// <returns></returns>
		public async Task SendMessageCaller(string message)
		{
			_logger.LogInformation($"SendMessageCaller===== {message}");
			await Clients.Caller.SendAsync(message);
		}

		/// <summary>
		/// 客户端连接服务端
		/// </summary>
		/// <returns></returns>
		public override Task OnConnectedAsync()
		{
			var id = Context.ConnectionId;

			var GroupSid = Context.User?.Claims?.FirstOrDefault(c => c.Type == ClaimTypes.GroupSid)?.Value ?? "";

			_logger.LogInformation($"客户端ConnectionId=>【{id}】已连接服务器！");

			if (_cache.TryGetValue(string.Format(WebConstCacheKey.UserCacheKey, Context.User?.Identity?.Name), out LoginModel loginUser))
			{
				var online = new OnlineUser
				{
					ConnectionId = id,
					UserName = loginUser.Account,
					GroupName = GroupSid,
					ActiveStatus = "在线"
				};

				WebConst.AddOnlineUser(online);
			}

			Groups.AddToGroupAsync(id, GroupSid);

			ResultModel result = new ResultModel()
			{
				Code = 0,
				Msg = "获取分组人数",
				OnlineUser = WebConst.OnlineUserList
			};

			Clients.Group(GroupSid).SendAsync("GetUsersResponse", result);

			return base.OnConnectedAsync();
		}

		/// <summary>
		/// 客户端断开连接
		/// </summary>
		/// <param name="exception"></param>
		/// <returns></returns>
		public override Task OnDisconnectedAsync(Exception exception)
		{
			var id = Context.ConnectionId;
			_logger.LogInformation($"客户端ConnectionId=>【{id}】已断开服务器连接！");

			if (_cache.TryGetValue(string.Format(WebConstCacheKey.UserCacheKey, Context.User?.Identity?.Name), out LoginModel loginUser))
			{
				var info = TestUsers.UserList.Find(u => u.UserName == loginUser.Account && u.Password == loginUser.Pwd);

				var online = new OnlineUser
				{
					ConnectionId = id,
					UserName = info.UserName,
					GroupName = info.GroupName,
					ActiveStatus = "离线"
				};
				WebConst.DeleteOnlineUser(online);

				ResultModel result = new ResultModel()
				{
					Code = 0,
					Msg = "获取分组人数",
					OnlineUser = WebConst.OnlineUserList
				};

				Groups.RemoveFromGroupAsync(id, info.GroupName);
			}
			return base.OnDisconnectedAsync(exception);
		}

		public async Task ReceiveLog(object data)
		{
			data = ReadHelper.Read();
			await Clients.All.SendAsync("ReceiveLog");
		}
	}
}